﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;

public partial class DemoGridView_CustomizeGridView : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
            LoadManufacturer();
    }

    private void LoadManufacturer()
    {
        SqlDataAdapter da = new SqlDataAdapter("select * from Manufacturer", DataAccess.ConnectionString);
        DataSet ds = new DataSet();
        da.Fill(ds);
        grvM.DataSource = ds.Tables[0];
        grvM.DataBind();
    }
    protected void grvM_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowIndex < 0) return;
        if (grvM.EditIndex != e.Row.RowIndex)
        {
            //search linkbutton delete for add confirm OK, Cancel
            ImageButton btndel = (ImageButton)e.Row.Cells[6].Controls[0];
            btndel.Attributes.Add("onclick", "return confirm('Do you want delete this row?')");
        }
        ImageButton btnactive = (ImageButton)e.Row.Cells[5].FindControl("imgActive");
        if(btnactive.ToolTip=="0")
            btnactive.ImageUrl="~/icons/checkbox_checked_icon.png";
        else
            btnactive.ImageUrl = "~/icons/stop.png";

    }
    protected void grvM_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {

    }
    protected void grvM_RowEditing(object sender, GridViewEditEventArgs e)
    {
        grvM.EditIndex = e.NewEditIndex;
        LoadManufacturer();
    }
    protected void grvM_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {

    }
    protected void grvM_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {

    }
    protected void grvM_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName.StartsWith("active"))
        {
            
            string id = e.CommandArgument.ToString();
            string active = e.CommandName.Substring(e.CommandName.Length - 1);
            SqlCommand cmd = DataAccess.Connection.CreateCommand();
            cmd.CommandText = "update manufacturer set active=@active where mid=@mid";
            //add value to parameter
            if(active=="1")
                cmd.Parameters.AddWithValue("@active", 0);
            else
                cmd.Parameters.AddWithValue("@active", 1);
            cmd.Parameters.AddWithValue("@mid", id);
            cmd.ExecuteNonQuery();
            LoadManufacturer();
        }
    }
    protected void grvM_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        grvM.PageIndex = e.NewPageIndex;
        LoadManufacturer();
    }
}
